package com.example.demo.zip.test;

import java.io.*;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Author: zjq
 * @Date: create in 2022/9/22 14:45
 */
public class ZipResult {
    /**
     * zip压缩---目前只支持一个文件夹下所有的文件
     * @param args
     */
    //设置输入输出路径
    private static String ZIP_FILE = "C:\\Users\\THINK\\Downloads\\new.zip";//压缩包文件名
    private static String JPG_FILE_PATH = "C:\\Users\\THINK\\Downloads\\test";//要压缩的文件名，文件是图片

    //实现方法
    public static void zipFile() {
        File zipFile = new File(ZIP_FILE);
        File fileModel = new File(JPG_FILE_PATH);
        File[] fileConent = fileModel.listFiles();
        try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
             BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(zipOut)) {
            //开始时间
            long beginTime = System.currentTimeMillis();
            for (File fc : fileConent) {
                try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(fc))) {
                    ZipEntry entry = new ZipEntry(fc.getName());
                    //核心，和复制粘贴效果一样，并没有压缩，但速度很快
                    entry.setMethod(ZipEntry.STORED);
                    entry.setSize(fc.length());
                    entry.setCrc(getFileCRCCode(fc));
                    zipOut.putNextEntry(entry);
                    int len = 0;
                    byte[] data = new byte[8192];
                    while ((len = bufferedInputStream.read(data)) != -1) {
                        bufferedOutputStream.write(data, 0, len);
                    }
                    bufferedInputStream.close();
                    bufferedOutputStream.flush();
                }
            }
            printInfo(beginTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //时间计算
    public static void printInfo(long beginTime) {
        long endTime = System.currentTimeMillis();
        long total = endTime - beginTime;
        System.out.println("耗時：" + total);
    }

    //获取CRC32
    public static long getFileCRCCode(File file) throws Exception {
        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
        CRC32 crc32 = new CRC32();
        //CheckedInputStream一种输入流，它还维护正在读取的数据的校验和。 然后可以使用校验和来验证输入数据的完整性。
        CheckedInputStream checkedinputstream = new CheckedInputStream(bufferedInputStream, crc32);
        while (checkedinputstream.read() != -1) {
        }
        checkedinputstream.close();
        bufferedInputStream.close();
        return crc32.getValue();
    }

    //主函数
    public static void main(String[] args) {
        zipFile();
    }


}
